import {Injectable, UnauthorizedException} from "@nestjs/common";
import {PassportStrategy} from "@nestjs/passport";
import {ExtractJwt, Strategy} from "passport-jwt";
import {ConfigService} from "@nestjs/config";
import {RedisService} from "../../common/database/redis/redis.service";
import {UserLoginConfig} from "../../../common/interfaces/user";
import {JwtPayload} from "../../../common/types/jwt.type";
import {USER} from "../../../common/constants/redisKey";

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
    constructor(
        private readonly configService: ConfigService,
        private readonly redisService: RedisService
    ) {
        super({
            jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
            ignoreExpiration: false,
            secretOrKey: configService.get("jwt.secret")
        });
    }

    async validate(payload: JwtPayload) {
        const {userId, username, version: requestTokenVersion} = payload
        const user: UserLoginConfig = await this.redisService.getValue<UserLoginConfig>(`${USER}:${userId}`) as UserLoginConfig
        if (!user) throw new UnauthorizedException("用户未登录")
        const {version: newVersion} = user
        if (requestTokenVersion !== newVersion) throw new UnauthorizedException("登录信息过期")
        return {userId, username, version: newVersion};

    }
}
